#include <memory.h>

#include "lib.h"

#include "client.h"
#include "speedtest.h"

unsigned char SpeedTest::m_data[1024] =
{
	0x5e, 0x66, 0xe7, 0x0b, 0x2c, 0xe2, 0x58, 0xe4, 0x12, 0x69, 0x38, 0xb6, 0x28, 0xc7, 0x2c, 0xc8,
	0xf2, 0x8b, 0xd6, 0xee, 0x3c, 0xbb, 0xad, 0x7d, 0xe1, 0x76, 0x38, 0xb7, 0x20, 0x63, 0xa4, 0x82,
	0x19, 0xdd, 0x38, 0x66, 0xb3, 0x2d, 0x80, 0x01, 0x51, 0xd9, 0x98, 0x4f, 0x37, 0x9b, 0x90, 0x61,
	0x75, 0x48, 0x36, 0x58, 0x03, 0x83, 0x8e, 0xa5, 0xe5, 0xf0, 0x18, 0x7a, 0x04, 0x57, 0x16, 0x1a,
	0x69, 0x65, 0x10, 0x53, 0x86, 0x27, 0x3d, 0xd9, 0x2e, 0xb4, 0xf0, 0xf8, 0x33, 0x38, 0xe9, 0xc7,
	0x04, 0xf1, 0x59, 0x26, 0xa2, 0xc2, 0x96, 0x1b, 0xe1, 0x09, 0xcf, 0x66, 0xbb, 0x37, 0xa9, 0xe6,
	0x6f, 0x9b, 0x7e, 0x72, 0xb7, 0x74, 0xe6, 0x85, 0x9d, 0x98, 0xaa, 0x7a, 0x24, 0xd2, 0xe9, 0xbb,
	0xf6, 0xed, 0x3c, 0x2e, 0x57, 0x90, 0xa4, 0xa0, 0xb3, 0x82, 0xb0, 0x19, 0xee, 0xac, 0x65, 0xb0,
	0x78, 0x06, 0xc0, 0x0a, 0x57, 0xc9, 0xa7, 0x70, 0x98, 0x1a, 0x87, 0xe7, 0x19, 0x7f, 0x5e, 0x7d,
	0x8a, 0x79, 0x74, 0xee, 0x7a, 0x85, 0x7a, 0x00, 0x80, 0xc8, 0x23, 0x64, 0xf9, 0x8c, 0x24, 0x08,
	0xda, 0x7d, 0x2e, 0x93, 0x25, 0x71, 0xa2, 0x0d, 0x40, 0x99, 0x21, 0x33, 0xaf, 0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, 0xdc, 0xf5, 0xbb, 0xc6, 0xec, 0x93,
	0x46, 0xd8, 0xda, 0x61, 0x70, 0xda, 0x68, 0x3d, 0x56, 0x0f, 0x76, 0x6d, 0x40, 0xd6, 0x13, 0x8e,
	0xf3, 0x01, 0x5e, 0x6b, 0xf3, 0x13, 0x50, 0xc7, 0x8f, 0xc1, 0x81, 0x8e, 0x88, 0xb0, 0x3c, 0x3b,
	0x05, 0x82, 0x20, 0x26, 0xa2, 0xa6, 0xe1, 0xbf, 0xb4, 0x36, 0xf9, 0x3c, 0x59, 0x12, 0x37, 0x47,
	0x9f, 0xfe, 0x13, 0x42, 0x30, 0x1f, 0xb0, 0xad, 0xc6, 0x7d, 0xbe, 0x57, 0x9f, 0xe3, 0x55, 0x77,
	0xcf, 0x45, 0xdf, 0x74, 0x8b, 0xb9, 0xb2, 0xed, 0xba, 0xdb, 0xb8, 0x18, 0xb4, 0x7b, 0x06, 0x5f,
	0xce, 0x9f, 0xec, 0x62, 0xae, 0x9d, 0xb2, 0x44, 0x5a, 0xc8, 0x59, 0x46, 0xf5, 0x48, 0xe4, 0xdf,
	0xe8, 0xe3, 0xd6, 0xa7, 0x8d, 0x3b, 0xc0, 0x46, 0xad, 0xc7, 0x8b, 0xbb, 0x0d, 0x71, 0x9e, 0x0b
};



SpeedTest::SpeedTest(Client* client)
:Protocol(client)
{
	m_loc = 0;
}

SpeedTest::~SpeedTest()
{
}

bool8
SpeedTest::recognize(uint8* Msg, uint32 Len)
{
	return (Msg[0] == 'T' && Len >= 1);
}

int32
SpeedTest::start(uint8* Msg, uint32 Len)
{
	return EM_Success;
}

static const int SPEED_TEST_BUFFER = 2048;

void
SpeedTest::netIn(int32 Amt)
{
	netOut(SPEED_TEST_BUFFER);
}

void
SpeedTest::netOut(int32 Amt)
{
    ASSERT( Amt == SPEED_TEST_BUFFER );
	ASSERT( Amt <= client->getOSize());

	uint8* obuf = client->getOBuf();
	uint32 bufsize = Amt;

	uint32 wrote = 0;

	while(wrote < bufsize)
	{
		uint32 start = m_loc % 1023;
		uint32 write = MIN(1024 - start, bufsize - wrote);

		memcpy(obuf + wrote, m_data + start, write);	//zero out buffer

		wrote += write;
		m_loc += wrote;
	}

	client->setOUsed(Amt);
	client->writeNet();
}